<template>
  <div>
    <div>
      <-- 定义两个按钮，一个添加按钮，  一个编辑按钮  -->
      <a-button type="primary" @click="showModal2">添加</a-button>
      <a-button type="primary" @click="showEditModal2">编辑</a-button>
      <-- 引入模态框，将modal框的确定和取消方法由此元素触发调用 -->
      <modal-add
        ref="collectionForm"
        :visible="visible"
        @cancel="dialogStatus==='add'?handleCancel2():handleEditCancel2()"
        @ok="dialogStatus==='add'?handleOk2():handleEditOk2()"
      />
    </div>

    <a-button type="primary" @click="del" :disabled="isAble">删除</a-button>
    <!-- form+modal -->
    <a-button type="primary" @click="showModal()" style="margin-left: 10px;">添加</a-button>
    <collection-create-form ref="collectionForm" :visible="visible" @cancel="handleCancel" @create="handleCreate"/>
    <a-button type="primary" @click="showModal" style="margin-left: 10px;">修改</a-button>
    <collection-create-form ref="collectionForm" :visible="visible" @cancel="handleCancel" @create="handleCreate"/>

    <!-- 查询表单 -->
    <div>
      <a-form layout="inline" :form="form" @submit="handleSubmit">
        <a-form-item :validate-status="userNameError() ? 'error' : ''" :help="userNameError() || ''">
          <a-input
            v-decorator="[
              'name',
              { rules: [{ required: true, message: 'Please input your name!' }] },
            ]"
            placeholder="name"
          >
            <a-icon slot="prefix" type="user" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item :validate-status="passwordError() ? 'error' : ''" :help="passwordError() || ''">
          <a-input
            v-decorator="[
              'id',
              { rules: [{ required: true, message: 'Please input your id!' }] },
            ]"
            placeholder="id"
          >
            <a-icon slot="prefix" type="lock" style="color:rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :disabled="hasErrors(form.getFieldsError())">
            Log in
          </a-button>
        </a-form-item>
      </a-form>
    </div>
    <a-table :columns="columns" :dataSource="dataMenu" :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" @change="handleTableChangeForMenu"/>
    <!-- 从后台动态获取数据 -->
    <div>
      <template>
        <a-table
          :columns="columns2"
          :rowKey="record => record.id"
          :dataSource="data2"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
        >
          <template slot="name" slot-scope="name">
            {{ name }}
          </template>
        </a-table>
      </template>
    </div>
  </div>
</template>
<script>
  import { mapActions } from 'vuex'
  import ModalAdd from '@/components/ModalAdd'
  const CollectionCreateForm = {
    props: ['visible'],
    beforeCreate () {
      this.form = this.$form.createForm(this, { name: 'form_in_modal' });
    },
    template: `
      <a-modal
        :visible="visible"
        title='Create a new collection'
        okText='Create'
        @cancel="() => { $emit('cancel') }"
        @ok="() => { $emit('create') }"
      >
        <a-form layout='vertical' :form="form">
          <a-form-item label='name'>
            <a-input  v-model="mdl.name"
              v-decorator="[
                'name',
                {
                  rules: [{ required: true, message: 'Please input the name of collection!' }],
                }
              ]"
            />
          </a-form-item>
          <a-form-item label='component'>
            <a-input
              type='textarea'
              v-decorator="['component']"
            />
          </a-form-item>
          <a-form-item label='redirect'>
            <a-input
              type='textarea'
              v-decorator="['redirect']"
            />
          </a-form-item>
          <a-form-item label='title'>
            <a-input
              type='textarea'
              v-decorator="['title']"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    `
  };
  const columns2 = [
      {
        title: 'Name',
        dataIndex: 'name',
        sorter: true,
        width: '20%',
        scopedSlots: { customRender: 'name' }
      },
      {
        title: 'id',
        dataIndex: 'id',
        width: '20%'
      },
      {
        title: 'des',
        dataIndex: 'des',
        width: '20%'
      },
      {
        title: 'meta',
        dataIndex: 'meta',
        width: '20%'
      },
      {
        title: 'component',
        dataIndex: 'component'
      }
    ];

  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: 'component',
      dataIndex: 'component',
      key: 'component',
      width: '12%'
    },
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      width: '12%'
    },
    {
      title: 'meta',
      dataIndex: 'meta',
      key: 'meta',
      width: '12%'
    },
    {
      title: 'des',
      dataIndex: 'des',
      width: '30%',
      key: 'des'
    }
  ];

  function hasErrors (fieldsError) {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  }

  export default {
    name: 'Menu',
    components: { CollectionCreateForm, ModalAdd },
    data () {
      return {
        data2: [],
        pagination: { 'pageNum': 1, 'pageSize': 5 },
        loading: false,
        columns2,
        dataMenu: [],
        columns,
        hasErrors,
        form: this.$form.createForm(this, { name: 'horizontal_login' }),
        visible: false,
        selectedRowKeys: [],
        isAble: true,
        dialogStatus: '',
        mdl: {}
      };
    },
    mounted () {
      this.$nextTick(() => {
        // To disabled submit button at the beginning.
        this.form.validateFields();
      });
      this.fetchs({
          pageSize: 5,
          pageNum: 1
      });
      this.fetchs2({
          pageSize: 5,
          pageNum: 1
      });
    },
    methods: {
      ...mapActions(['MenuGet', 'MenuAdd', 'MenuList', 'Menus', 'MenuDel']),
      edit (record) {
        debugger;
        const { form: { setFieldsValue } } = this
        this.visible = true
        this.$nextTick(() => {
          setFieldsValue({ taskName: 'test' })
        })
      },
       // 处理添加方法
      showModal2 () {
        this.visible = true;
        this.dialogStatus = 'add';
      },
      handleCancel2 () {
        this.visible = false;
        this.dialogStatus = ''
        console.log('add cancel')
      },
      handleOk2 () {
        console.log('add ok')
      },
      // 处理编辑的方法
      showEditModal2 () {
        this.type = 'edit';
        this.visible = true;
      },
      handleEditCancel2 () {
        this.visible = false;
        this.dialogStatus = ''
        console.log('edit cancel')
      },
      handleEditOk2 () {
        this.visible = true;
        console.log('edit ok')
      },
      onSelectChange (selectedRowKeys) {
        debugger;
        // console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.selectedRowKeys = selectedRowKeys;
        if (this.selectedRowKeys.length === 1) {
          this.isAble = false
          this.$message.info(this.selectedRowKeys.length)
        } else {
          this.isAble = true
          this.$message.info(this.selectedRowKeys.length)
        }
      },
      userNameError () {
            const { getFieldError, isFieldTouched } = this.form;
            return isFieldTouched('userName') && getFieldError('userName');
      },
      // Only show error after a field is touched.
      passwordError () {
        const { getFieldError, isFieldTouched } = this.form;
        return isFieldTouched('password') && getFieldError('password');
      },
      handleSubmit (e) {
        debugger
        const {
          MenuGet
        } = this
        e.preventDefault();
        this.form.validateFields((err, values) => {
          if (!err) {
            // console.log('Received values of form: ', values);
            const menuParams = { ...values }
            menuParams.name = values.name
            MenuGet(menuParams)
              .then((res) => {
                console.log(res)
              })
              .catch(err => this.requestFailed(err))
              .finally(() => {
                // console.log('菜单获取，finally')
                this.fetchs({
                  pageSize: 5,
                  pageNum: 1
                });
              })
          }
        });
      },

      handleTableChange (pagination, filters, sorter) {
        debugger
        // console.log(pagination);
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetchs({
          pageSize: pagination.pageSize,
          pageNum: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters
        });
      },
      fetchs (params = {}) {
        debugger
        const {
          MenuList
        } = this
        // console.log('params:', params);
        this.loading = true;
        MenuList({
            params
        }).then(data => {
          const pagination = { ...this.pagination };

          // Read total count from server
          // pagination.total = data.totalCount;
          pagination.total = data.total;
          // pagination.pageSize = data.pageSize;
          // pagination.current = data.pageNmn;
          this.loading = false;
          this.data2 = data.results;
          this.pagination = pagination;
          // console.log('this.pagination' + this.pagination)
        });
      },
      handleTableChangeForMenu (pagination, filters, sorter) {
        debugger
        // console.log(pagination);
        const pager = { ...this.pagination };
        pager.current = pagination.current;
        this.pagination = pager;
        this.fetchs2({
          pageSize: pagination.pageSize,
          pageNum: pagination.current,
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...filters
        });
      },
      fetchs2 (params = {}) {
        debugger
        const {
          Menus
        } = this
        this.loading = true;
        Menus({
            params
        }).then(data => {
          this.isAble = true;
          this.$message.info(data.total)
          const pagination = { ...this.pagination };
          pagination.total = data.total;
          this.loading = false;
          this.dataMenu = JSON.parse(data.results);
          this.pagination = pagination;
        });
      },
      showModal () {
         var s = this.selectedRowKeys[0]
         // this.$message.info('modal update', this.selectedRowKeys[0])
         const {
           MenuGet
         } = this
         MenuGet({
             s
         }).then(data => {
           debugger
           // this.mdl = data.result;
           this.mdl = Object.assign({}, data.result)
           this.$message.info('MenuGet' + data.result)
           console.log(data)
         });
        debugger;
        this.visible = true;
        this.$refs.modal.edit(this.mdl);
      },
      handleCancel () {
        this.visible = false;
      },
      handleCreate () {
        const form = this.$refs.collectionForm.form;
        form.validateFields((err, antMenu2) => {
          if (err) {
            return;
          }
          // console.log('Received values of form: ', antMenu2);
          this.$message.info('modal form submit', antMenu2)
          const {
            MenuAdd
          } = this
          // console.log('params:', antMenu2);
          this.loading = true;
          MenuAdd({
              antMenu2
          }).then(data => {
            debugger
            // console.log('-----------MenuAdd--------' + data)
          });
          form.resetFields();
          this.visible = false;
          this.fetchs({
              pageSize: 5,
              pageNum: 1
          });
          this.fetchs2({
              pageSize: 5,
              pageNum: 1
          });
        });
      },
      del (selectedRowKeys) {
        // console.log(this.selectedRowKeys[0])
        const id = this.selectedRowKeys[0];
        this.$message.info(id)
        const {
          MenuDel
        } = this
        // console.log('params:', id);
        this.loading = true;
        MenuDel({
            id
        }).then(data => {
          // console.log('data' + data)
        });

        this.fetchs2({
            pageSize: 5,
            pageNum: 1
        });
        this.selectedRowKeys = []
      }
    }
  };

</script>
